import { PlusOutlined, DownOutlined } from '@ant-design/icons';
import { Button, message, Divider, Popconfirm, Tree } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { FormattedMessage } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import moment from 'moment';
import { getList, removeField, getTree } from './api';
import styles from './index.less';
import UpdateForm from './components/UpdateForm';

// 主数据格式化
const setList = arr => {
  const newTreeData = [];
  arr.map(item => {
    // const obj = { ...item }
    const obj = {
      id: item.deptId,
      value: item.deptId,
      title: item.deptName,
      pId: item.parentId,
      // isLeaf: false
    };
    if (item.children && item.children.length) {
      obj.children = setList(item.children);
    } else {
      obj.children = null;
    }
    newTreeData.push(obj);
    return '';
  });
  return newTreeData;
};

const TableList = () => {
  const actionRef = useRef();

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async id => {
    const hide = message.loading('正在删除');

    try {
      const msg = await removeField(id);
      hide();
      if (msg.code === 0) {
        message.success('删除成功！');
        if (actionRef.current) {
          actionRef.current.reload();
        }
        return true;
      }
      message.error(msg.msg || '删除失败，请重试');
      return false;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  // 更新数据 组件 ------------------------------------------------------------------

  const [type, setType] = useState();

  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [updataData, setUpdataData] = useState({});
  const currentIndex = actionRef?.current?.pageInfo?.total || 0; // 默认排序

  const [selectedRowsState, setSelectedRows] = useState(false); //多选 删除
  const [categoryData, setCategoryData] = useState(false); //多选 删除

  const [pagination, setPagination] = useState({ current: 1, pageSize: 20 });

  const [selectedKeys, setSelectedKeys] = useState([]); //当前选择前置机
  const [keyValue, setKeyValue] = useState(null);

  const ProTableOoChange = ({ current, pageSize }) => {
    setPagination({ current, pageSize });
  };

  const closeUpdateForm = () => {
    handleUpdateModalVisible(false);
  };

  const setUpdateForm = param => {
    setType('updata');
    handleUpdateModalVisible(true);
    setUpdataData(param);
  };

  const updataSuccess = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  /**
   * @zh-CN 列表数据
   * @param fields
   */

  const getListData = async fields => {
    try {
      const data = await getList({ ...fields, catagolueid: keyValue });
      if (data && data.code === 0) {
        return { data: data.data?.list || [], total: data.data?.total || 0 };
      }
      message.error(data.msg || '请求失败，请重试');
      return;
    } catch (error) {
      message.error('请求失败，请重试');
      return false;
    }
  };

  const setDataBase = () => {};

  // 添加
  const add = () => {
    setType('add');
    setUpdataData({});
    handleUpdateModalVisible(true);
  };
  // ----------------------------------------------结束------------------------------------------------------

  const getTreeData = () => {
    getTree().then(res => {
      if (res.code === 0) {
        setCategoryData(res.data);
        setKeyValue(res.data[0]?.key);
        setSelectedKeys([res.data[0]?.key]);
      }
    });
  };

  const onSelect = (value, data) => {
    setSelectedKeys(value);
    setKeyValue(data.node.key);
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  useEffect(() => {
    getTreeData();
  }, []);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns = [
    {
      title: '序号',
      valueType: 'option',
      dataIndex: '',
      render(text, record, index) {
        return (
          <span key={index}>{(pagination.current - 1) * pagination.pageSize + index + 1}</span>
        );
      },
    },

    {
      title: '数据源名称',
      dataIndex: 'name',
    },
    {
      title: '数据库名称',
      dataIndex: 'dbname',
      hideInSearch: true,
    },
    {
      title: '数据库类型',
      dataIndex: 'dbtype',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'state',
      valueType: 'option',
      hideInSearch: true,

      render: (_, record) => {
        return <>{record.state === '0' ? '禁用' : '激活'}</>;
      },
    },
    {
      title: '链接状态',
      dataIndex: 'openstate',
      hideInSearch: true,

      valueEnum: {
        0: {
          text: '下线',
          status: 'Default',
        },
        1: {
          text: '在线',
          status: 'Success',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'option',
      render: (_, record) => {
        return <>{moment(record.createTime).format('YYYY-MM-DD')}</>;
      },
    },
    {
      title: '操作',
      dataIndex: 'opt',
      valueType: 'option',
      render: (_, record, index) => {
        const text = (
          <>
            <Button type="link" onClick={() => setUpdateForm(record, index)}>
              编辑
            </Button>
            <Divider type="vertical" />
            <Popconfirm
              placement="topRight"
              title="确实要删除此条信息吗？"
              onConfirm={() => handleRemove(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link">删除</Button>
            </Popconfirm>
          </>
        );
        return <>{text}</>;
      },
    },
  ];
  return (
    <PageContainer>
      <div className={styles.wrap}>
        <div className={styles.left}>
          <Tree
            showLine
            switcherIcon={<DownOutlined />}
            onSelect={onSelect}
            treeData={categoryData}
            selectedKeys={selectedKeys}
          />
        </div>
        <div className={styles.right}>
          {keyValue && (
            <ProTable
              actionRef={actionRef}
              rowKey={record => record.id}
              search={{
                labelWidth: 120,
              }}
              toolBarRender={() => [
                <Button type="primary" key="primary" onClick={add}>
                  <PlusOutlined />{' '}
                  <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
                </Button>,
                // <Popconfirm
                //   placement="topRight"
                //   title="确实要重置数据源吗？"
                //   onConfirm={() => setDataBase()}
                //   okText="确定"
                //   cancelText="取消"
                // >
                //   <Button type="primary" danger>
                //     重置数据源
                //   </Button>
                // </Popconfirm>,
                // <Popconfirm
                //   placement="topRight"
                //   title="确实要重置数据源吗？"
                //   onConfirm={() => setDataBase()}
                //   okText="确定"
                //   cancelText="取消"
                // >
                //   <Button type="primary" danger>
                //     更新表结构
                //   </Button>
                // </Popconfirm>,
              ]}
              request={getListData}
              columns={columns}
              onChange={ProTableOoChange}
              // rowSelection={{
              //   onChange: (_, selectedRows) => {
              //     setSelectedRows(selectedRows)
              //   }
              // }}
            />
          )}
          {/* <FooterToolbar
            extra={
              <div>
                <FormattedMessage id='pages.searchTable.chosen' defaultMessage='已选择' />{' '}
                <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
                <FormattedMessage id='pages.searchTable.item' defaultMessage='项' />
                &nbsp;&nbsp;
              </div>
            }>
            <Button type='primary'>批量删除</Button>
          </FooterToolbar> */}
        </div>
      </div>

      <UpdateForm
        visible={updateModalVisible}
        onCancel={closeUpdateForm}
        data={updataData}
        unitid={keyValue}
        onSuccess={updataSuccess}
        type={type}
        currentIndex={currentIndex}
      />
    </PageContainer>
  );
};

export default TableList;
